<template>
  <div>
    <button @click="addRow" class="btn_operation_add">
      <img src="~@/assets/img/grzx/add.png" alt="" />
      新增
    </button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in tableHeader"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
      >
        <template slot-scope="scope">
          <form-item
            :formItem="item"
            v-model="scope.row[item.prop]"
          ></form-item>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="60">
        <template slot-scope="scope">
          <el-link type="primary" @click="deleteRow(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import FormItem from './components/form-item.vue'
export default {
  components: { FormItem },
  props: {
    data: Array,
    tableHeader: Array
  },
  data () {
    return {
      tableData: []
    }
  },
  watch: {
    data (val) {
      this.tableData = val
    }
  },
  mounted () {
    if (this.data) {
      this.tableData = this.data
    }
  },
  methods: {
    // 添加
    addRow () {
      // 解析表头获取需要新增的字段
      const obj = {}
      for (let el of this.tableHeader) {
        if (el.type === 'number') {
          obj[el.prop] = 0
        } else {
          obj[el.prop] = ''
        }
      }
      obj.id = new Date().getTime()
      this.tableData.push(obj)
    },
    // 删除
    deleteRow (row) {
      this.tableData = this.tableData.filter(el => {
        return el.id !== row.id
      })
    }
  }
}
</script>
<style lang="scss" scoped></style>
